package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.vo.SocialUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuth2Controller {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private MemberFeignService memberFeignService;
    @GetMapping("/oauth2.0/gitee/success")
    public String getiee(@RequestParam("code") String code, HttpServletResponse httpResponse, HttpSession session) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("grant_type","authorization_code");
        map.put("client_id","4f907783c38cfa3e935e534fe30109dd25d17ac5c0dd883dc057ec8f9cd6a631");
        map.put("client_secret","338966eedb745d905ff2fec54f9e4ca9171700f05cef5cabe276ffd195134977");
        map.put("redirect_uri","http://auth.xiaochao.love/oauth2.0/gitee/success");
        map.put("code",code);
        ResponseEntity<String> response = restTemplate.postForEntity("https://gitee.com/oauth/token", map, String.class);
        System.out.println("code"+response.getStatusCodeValue());
        if (response.getStatusCodeValue()==200){
            String json = response.getBody();
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            R oauth2login = memberFeignService.oauth2login(socialUser);
            if (oauth2login.getCode()==0){
                MemberRespVo data = oauth2login.getData("data", new TypeReference<MemberRespVo>() {
                });
                System.out.println("用户信息"+data);
                session.setAttribute("loginUser",data);
//                httpResponse.addCookie(new Cookie("JSESSIONID",data).setDomain());
                return "redirect:http://www.xiaochao.love";
            }else {
                return "redirect:http://auth.xiaochao.love/login.html";
            }
        }else {
            return "redirect:http://auth.xiaochao.love/login.html";
        }
    }
}
